package com.jason.schedulemigrationtest.controller;


import com.jason.schedulemigrationtest.common.DataMigrationScheduler;
import com.jason.schedulemigrationtest.common.R;
import com.jason.schedulemigrationtest.po.ExpressOrder;
import com.jason.schedulemigrationtest.service.ExpressOrderQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/express-orders")
@Slf4j
public class ExpressOrderController {


    @Resource
    private DataMigrationScheduler dataMigrationScheduler;
    @Resource
    private ExpressOrderQueryService expressOrderQueryService;

    /**
     * 根据订单号查询订单（自动路由到热数据或冷数据）
     */
    @GetMapping("/query/{orderId}")
    public R queryByOrderId(@PathVariable Long orderId) {
        try {
            ExpressOrder order = expressOrderQueryService.queryByOrderId(orderId);
            if (order != null) {
                return R.builder().code(200).msg("查询成功").data(order).build();
            } else {
                return R.builder().code(404).msg("订单不存在").build();
            }
        } catch (Exception e) {
            log.error("查询订单异常: {}", e.getMessage(), e);
            return R.builder().code(500).msg("查询异常: " + e.getMessage()).build();
        }
    }

    /**
     * 时间格式 yyyy-MM-dd
     * 根据时间范围查询订单（智能路由）
     */
    @GetMapping("/query/range")
    public R queryByTimeRange(@RequestParam String startTime, @RequestParam String endTime) {
        try {
            List<ExpressOrder> orders = expressOrderQueryService.queryByTimeRange(startTime, endTime);
            return R.builder().code(200).msg("查询成功").data(orders).build();
        } catch (Exception e) {
            log.error("时间范围查询异常: {}", e.getMessage(), e);
            return R.builder().code(500).msg("查询异常: " + e.getMessage()).build();
        }
    }

    /**
     * 手动触发数据迁移
     */
    @PostMapping("/migrate")
    public R triggerMigration() {
        try {
            dataMigrationScheduler.dataMigrationTask();
            log.info("手动迁移数据成功");
            return R.builder().code(200).msg("数据迁移成功").build();
        } catch (Exception e) {
            log.info("手动迁移数据异常: {}", e.getMessage(), e);
            return R.builder().code(500).msg("数据迁移异常 "+e.getMessage()).build();
        }
    }
}
